package com.keta.foundation.exception;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.keta.foundation.controller.LoginController;
import com.keta.foundation.util.dwz.AjaxObject;

public class SysHandlerExceptionResolver implements HandlerExceptionResolver {

	private static final Logger logger = LoggerFactory.getLogger(SysHandlerExceptionResolver.class);

	/**
	 * 处理异常全局异常
	 */
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
			Exception ex) {

		System.out.println(request.getHeader("X-Requested-With"));
		System.out.println(request.getParameter("ajax"));
		
		response.setCharacterEncoding("UTF-8");
		

		if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
			System.out.println("###SysHandlerExceptionResolver");
			String str = "";
			if (ex instanceof ServiceException) {
				str = AjaxObject.newError(ex.getMessage()).toString();
			}else if(ex instanceof UnauthorizedException){
				str = AjaxObject.newError("没有权限！").toString();
			}else if(ex instanceof  BindException){
				str = "数据验证不通过,请检查数据格式!";
			}else {
				str = AjaxObject.newError("未知错误，请联系管理员").toString();
			}
			try {
				response.getWriter().print(str);
				response.getWriter().flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			// 不是ajax请求
			Map<String,String> map = new HashMap<String,String>();
			String message = "";
			if (ex instanceof ServiceException) {
				message = ex.getMessage();
			}else if(ex instanceof UnauthorizedException){
				message = "没有权限！";
			}else if(ex instanceof  BindException){
				message = "数据验证不通过!";
			}else {
				message = "未知错误，请联系管理员";
			}
			map.put("message", message);
			return new ModelAndView("error/500",map);
		}

		logger.error(ex.toString());
		return null;
	}

}
